import tarfile
import os
import urlparse
from pyurl.url import scheme_registry
from pyurl.protocols.archive import ArchiveConnection, ArchiveURL

class TarFileObject(object):
    def __init__(self, archive, filename):
        self.archive = archive
        self.filename = filename
        
    def read(self):
        return self.archive.read(self.filename)
    
class TarConnection(ArchiveConnection):
    def open_archive(self, file):
        return tarfile.open(str(file), "r", file.open("r"))
            
    def exists(self, path):
        return path[1:] in self.archive.getnames()
        
    def open_file(self, path, mode):
        if self.exists(path):
            return self.archive.extractfile(path[1:])
        else:
            raise IOError(2, "No such file or directory '"+path[1:]+"'")
    
        
class TarURL(ArchiveURL):
    _scheme = "tar"
    _connection_type = TarConnection

scheme_registry.register(TarURL)